<template>
    <div>
        <el-card>
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>商品管理</el-breadcrumb-item>
                <el-breadcrumb-item>商品列表</el-breadcrumb-item>
            </el-breadcrumb>


            <el-button type="primary" size="small" @click="addHandle" style="margin-top: 15px;">添加</el-button>

            <el-table :data="productList" border style="width: 100%" height="620"
                :header-cell-style="{ background: '#409EFF', color: '#FFF' }">
                <el-table-column prop="productName" label="商品图片" width="120">
                    <template slot-scope="prop">
                        <el-image :src="prop.row.productImg" class="image-control" :previewSrcList="[prop.row.productImg
                ]"></el-image>
                    </template>
                </el-table-column>
                <el-table-column prop="productName" label="商品名称"></el-table-column>
                <el-table-column prop="formatName" label="规格名称"></el-table-column>
                <!-- <el-table-column prop="productDate" label="生产日期"></el-table-column>
                <el-table-column prop="productValidity" label="效期"></el-table-column> -->
                <el-table-column prop="factoryName" label="厂商"></el-table-column>
                <el-table-column prop="productStatus" label="状态">
                    <template slot-scope="scope">
                        <el-tag type="success" v-if="scope.row.productStatus == 1">启用</el-tag>
                        <el-tag type="danger" v-else>禁用</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button size="small" @click="editHandle(scope.row)">修改</el-button>
                        <el-button size="small" icon="el-icon-top" @click="statusHandle(scope.row, 1)"
                            v-if="scope.row.productStatus == 0" plain>启用</el-button>
                        <el-button size="small" @click="statusHandle(scope.row, 0)" icon="el-icon-bottom"
                            v-else>禁用</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="paginationBox">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="pageNum" :page-sizes="[20, 50, 100]" :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper" :total="total">
                </el-pagination>
            </div>

            <!-- 添加商品弹窗 -->
            <el-dialog title="商品信息" :visible.sync="dialogVisible" width="30%" top="4%" :before-close="handleClose">
                <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                    <el-form-item label="商品主图" v-if="!editFlag">
                        <el-upload action="aa" class="avatar-uploader" :on-change="proChange" :auto-upload="false"
                            accept="*" ref="addProduct_pic" :show-file-list="false">

                            <template v-if="form.product_pic || form.imageUrl">
                                <img :src="form.imageUrl" class="avatar" />
                                <div class="addTip">点击更换图片</div>
                            </template>
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="商品名称" prop="productName">
                        <el-input v-model="form.productName" placeholder="请输入商品名称"></el-input>
                    </el-form-item>
                    <el-form-item label="规格名称" prop="formatName">
                        <el-input v-model="form.formatName" placeholder="请输入规格名称"></el-input>
                    </el-form-item>
                    <el-form-item label="厂商" prop="factoryId">
                        <el-select v-model="form.factoryId" placeholder="请选择">
                            <el-option v-for="item in factoryList" :key="item.factoryId" :label="item.factoryName"
                                :value="item.factoryId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <!-- <el-form-item label="生产日期" prop="productDate">
                        <el-date-picker type="date" value-format="yyyy-MM-dd" placeholder="选择日期"
                            v-model="form.productDate" style="width: 100%;"></el-date-picker>
                    </el-form-item>
                    <el-form-item label="效期" prop="productValidity">
                        <el-input v-model="form.productValidity" placeholder="请输入效期"></el-input>
                    </el-form-item> -->
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="handleClose">取 消</el-button>
                    <el-button type="primary" @click="submitHandle">确 定</el-button>
                </span>
            </el-dialog>
        </el-card>
    </div>
</template>
<script>

import { addProduct, listProduct, deleteProduct, updateProduct, updateProductStatus } from '../../network/product'
import { getFactoryByName } from '../../network/factory'
export default {
    name: 'product',
    data() {
        return {
            factoryList: [],// 厂商列表
            productList: [],
            dialogVisible: false,
            form: {
                productName: '',
                formatName: '',
                productDate: '',
                productValidity: '',
                factoryId: '',
                factoryName: '',
                imageUrl: '',
                product_pic: '',
                companyId: sessionStorage.companyId,
                productStatus: 1,
                categoryId: 1,
            },
            rules: {
                productName: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' },
                ],
                formatName: [
                    { required: true, message: '请输入商品规格名称', trigger: 'blur' },
                ],
                // productValidity: [
                //     { required: true, message: '请输入商品效期', trigger: 'blur' },
                // ],
                // productDate: [
                //     { required: true, message: '请选择商品生产日期', trigger: 'change' },
                // ],
                factoryId: [
                    { required: true, message: '请选择商品厂商', trigger: 'change' },
                ],
            },
            pageNum: 1,
            pageSize: 20,
            total: 0,
            editFlag: false,
        }
    },
    created() {
        this.getList()

        this.getFactoryList()
    },
    methods: {

        editHandle(obj) {
            this.form = obj
            this.form.imageUrl = obj.productImg
            this.form.product_pic = ''
            this.dialogVisible = true
            this.editFlag = true
            this.factoryList.forEach(ele => {
                if (ele.factoryName == this.form.factoryName) {
                    this.form.factoryId = ele.factoryId
                }
            })

            console.log(this.form);

        },


        delHandle(obj) {
            this.$confirm('是否删除该商品?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteProduct({
                    productId: obj.productId
                }).then(res => {
                    if (res.flag) {
                        this.getList()
                        this.$message.success('删除成功')
                    } else {
                        this.$message.warning('删除失败')
                    }
                })
            }).catch(() => {
            });


        },

        proChange(file) {
            this.form.imageUrl = URL.createObjectURL(file.raw);
            this.form.product_pic = file.raw;
        },

        submitHandle() {
            this.$refs.ruleForm.validate((valid) => {
                console.log(valid);

                if (!valid) return


                console.log(this.form);

                if (!this.editFlag && this.form.product_pic == '') {
                    this.$message.warning('请上传商品图片')
                    return
                }

                console.log(this.form.product_pic);
                console.log(this.form);


                this.factoryList.forEach(ele => {
                    if (ele.factoryId == this.form.factoryId) {
                        this.form.factoryName = ele.factoryName
                    }
                })

                console.log(this.form);

                // return

                var formData = new FormData();
                formData.append("file", this.form.product_pic);
                formData.append("productName", this.form.productName);
                formData.append("formatName", this.form.formatName);
                // formData.append("productDate", this.form.productDate);
                // formData.append("productValidity", this.form.productValidity);
                formData.append("factoryName", this.form.factoryName);
                formData.append("companyId", this.form.companyId);
                formData.append("productStatus", this.form.productStatus);
                formData.append("categoryId", this.form.categoryId);

                if (this.editFlag) {
                    updateProduct(this.form).then(res => {
                        console.log(res);
                        if (res.flag) {
                            this.getList();
                            this.handleClose();
                            this.dialogVisible = false
                            this.$message.success("修改成功");
                        } else {
                            console.log(res);
                            this.$message.success("修改失败");
                        }
                    });
                } else {
                    addProduct(formData).then(res => {
                        console.log(res);
                        if (res.flag) {
                            this.getList();
                            this.handleClose();
                            this.dialogVisible = false
                            this.$message.success("添加成功");
                        } else {
                            console.log(res);
                            this.$message.success("添加失败");
                        }
                    });
                }
            });

        },
        addHandle() {
            this.dialogVisible = true
            this.editFlag = false
        },
        check(obj) {
            console.log(obj);
        },
        handleClose() {
            this.dialogVisible = false
            this.$refs.ruleForm.resetFields()

            this.form.imageUrl = ''
            this.form.product_pic = ''
            this.form.factoryId = ''

            this.form = {
                productName: '',
                formatName: '',
                productDate: '',
                productValidity: '',
                factoryId: '',
                factoryName: '',
                imageUrl: '',
                product_pic: '',
                companyId: sessionStorage.companyId,
                productStatus: 1,
                categoryId: 1,
            }
        },

        getList() {
            listProduct({
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                companyId: sessionStorage.companyId,
            }).then(res => {
                if (res.flag) {
                    console.log(res);
                    this.productList = res.data.list
                    this.total = res.data.total
                }
            })
        },

        handleSizeChange(val) {
            this.pageSize = val
            this.getList()
        },
        handleCurrentChange(val) {
            this.pageNum = val
            this.getList()
        },
        getFactoryList() {
            getFactoryByName({
                pageNum: 1,
                pageSize: 100,
                factoryName: '',
                companyId: sessionStorage.companyId,
            }).then(res => {
                if (res.flag) {
                    console.log(res);
                    this.factoryList = res.data.list
                }
            })
        },


        statusHandle(obj, flag) {

            updateProductStatus({
                productId: obj.productId,
                status: flag
            }).then(res => {
                if (res.flag) {
                    this.getList()
                    this.$message.success('操作成功')
                } else {
                    this.$message.warning('操作失败')
                }
            })

        },

    }
}
</script>

<style lang="less" scoped>
.paginationBox {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}


.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    border: 1px dashed #dcdfe6;
    border-radius: 8px;
}

.image-control,
.avatar {
    display: block;
    border-radius: 8px;
    width: 100px;
    height: 100px;
}

.addTip {
    color: #409eff;
    text-decoration: underline;
    cursor: pointer;
}
</style>